package com.neusoft.neuiotms.dcom.controller.hn;

import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.google.common.collect.Lists;
import com.neusoft.bizcore.auth.common.bean.UserBean;
import com.neusoft.bizcore.web.dto.result.PageResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultDTO;
import com.neusoft.bizcore.web.dto.result.ResultListDTO;
import com.neusoft.bizcore.web.support.Searchable;
import com.neusoft.neuiotms.dcom.dto.hn.HnInspectionTaskDTO;
import com.neusoft.neuiotms.dcom.model.enums.HnInspectionTaskStatus;
import com.neusoft.neuiotms.dcom.service.hn.HnInspectionTaskService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Api(tags = "海南项目巡检任务管理")
@RestController
@RequestMapping(value = "/api/w/hn/inspection/task")
public class HnInspectionTaskController {
    @Autowired
    private HnInspectionTaskService hnInspectionTaskService;

    @ApiOperation("查询所有巡检任务")
    @GetMapping
    public ResultListDTO<HnInspectionTaskDTO> index(final Searchable searchable, final UserBean user) {
        return ResultListDTO.success(this.hnInspectionTaskService.index(searchable, user));
    }

    @ApiOperation("分页查询所有巡检任务")
    @GetMapping("/p")
    public PageResultDTO<HnInspectionTaskDTO> search(final Pageable pageable, final Searchable searchable,
            final UserBean user) {
        return PageResultDTO.success(this.hnInspectionTaskService.search(pageable, searchable, user));
    }

    @ApiOperation(value = "保存每日巡检任务结果")
    @RequestMapping(path = "/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<HnInspectionTaskDTO> update(@PathVariable final Long id,
            @RequestBody final HnInspectionTaskDTO dto, final UserBean user) {
        return ResultDTO.success(this.hnInspectionTaskService.update(id, dto, user));
    }

    @ApiOperation(value = "提交每日巡检任务结果")
    @RequestMapping(path = "/submit/{id}", method = {RequestMethod.PUT, RequestMethod.POST })
    public ResultDTO<HnInspectionTaskDTO> submit(@PathVariable final Long id,
            @RequestBody final HnInspectionTaskDTO dto, final UserBean user) {
        return ResultDTO.success(this.hnInspectionTaskService.submit(id, dto, user));
    }

    @ApiOperation("巡检计划详情")
    @GetMapping("/{id}")
    public ResultDTO<HnInspectionTaskDTO> details(@PathVariable final Long id) {
        return ResultDTO.success(this.hnInspectionTaskService.details(id));
    }

    @ApiOperation("删除巡检计划")
    @DeleteMapping("/{id}")
    public ResultDTO<Void> delete(@PathVariable final Long id) {
        this.hnInspectionTaskService.delete(id);
        return ResultDTO.success();
    }

    @ApiOperation("获得当前用户的任务数")
    @GetMapping("/task/number")
    public ResultDTO<Integer> getFinishedTaskfindByUserName(final UserBean user) {
        final List<HnInspectionTaskStatus> status =
                Lists.newArrayList(HnInspectionTaskStatus.finished);
        final int num = this.hnInspectionTaskService.getTaskCountByStatus(user, status);
        return ResultDTO.success(num);
    }

    @ApiOperation("获得当前用户的任务数")
    @GetMapping("/unfinished/task/number")
    public ResultDTO<Integer> getUnfinishedTaskCountByStatus(final UserBean user) {
        final List<HnInspectionTaskStatus> status =
                Lists.newArrayList(HnInspectionTaskStatus.notStarted, HnInspectionTaskStatus.inspecting);
        final int num = this.hnInspectionTaskService.getTaskCountByStatus(user, status);
        return ResultDTO.success(num);
    }

    @ApiOperation("统计报表")
    @GetMapping("/stats/report")
    public PageResultDTO<Map<String, Object>> reportStats(final Pageable pageable,
            @RequestParam final Map<String, Object> params, final UserBean user) {
        final Page<Map<String, Object>> result = this.hnInspectionTaskService.report(pageable, params, user);
        return PageResultDTO.success(result);
    }

    @ApiOperation("统计报表")
    @GetMapping(value = "/stats/export")
    public void exportStats(@RequestParam final Map<String, Object> params,
            final HttpServletResponse response, final UserBean user) {

        final Workbook workbook = this.hnInspectionTaskService.exportReport(params, user);
        OutputStream out = null;
        try {
            out = response.getOutputStream();
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("Content-disposition",
                    String.format("attachment; filename=%s",
                            URLEncoder.encode("巡检统计导出" + LocalDateTime.now() + ".xlsx", "UTF-8")));
            workbook.write(out);
            out.flush();
        } catch (final Exception e) {
            HnInspectionTaskController.log.error("巡检统计导出失败", e);
        } finally {
            try {
                out.close();
            } catch (final IOException e) {
                HnInspectionTaskController.log.error("巡检统计导出关闭流失败", e);
            }
        }
    }
}
